<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :error.sync="error"
    error-text="加载失败，请点击重试"
    @load="onLoad"
  >
    <CommentItem
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
    />
    <!--reply-click是通过子组件把当前评论项传回给父组件 -->
  </van-list>
</template>

<script>
import { getComments } from '@/api/comment'
import CommentItem from './comment-item.vue'
export default {
  name: 'CommentList', // 评论列表
  components: {
    CommentItem
  },
  props: {
    source: {
      type: [String, Object, Number],
      required: true
    },
    // 要传递一个对象的时候要通过函数返回的形式
    list: {
      type: Array,
      default: () => []
    },
    type: {
      type: String,
      validator(value) {
        return ['a', 'c'].includes(value)
      },
      default: 'a'
    }
  },
  data() {
    return {
      // list: [],
      loading: false,
      finished: false,
      offset: null, // 获取下一页的数据标记
      limit: 10,
      error: false
    }
  },
  created() {
    // 当获取全部评论列表的时候就立即触发onload事件
    if (this.type === 'a') {
      this.onLoad()
    }
  },
  methods: {
    async onLoad() {
      try {
        const { data } = await getComments({
          type: this.type, // 评论类型，a 代表对文章的评论，c 代表评论的回复
          // !#1
          source: this.source.toString(), // 源 id，文章 id 或评论 id
          offset: this.offset,
          limit: this.limit
        })
        const { results } = data.data
        this.list.push(...results)
        // 把总数量传递到父级
        this.$emit('onload-success', data.data)
        this.loading = false
        if (results.length) {
          this.offset = data.data.last_id
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
        this.$toast('获取失败')
      }
    }
  }
}
</script>

<style></style>
